package top.lixunda.ecommerce.server.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import top.lixunda.commerce.common.core.entity.MessageObject;
import top.lixunda.common.validate.XumValid;
import top.lixunda.ecommerce.server.business.BaseController;
import top.lixunda.ecommerce.server.business.api.entity.cache.CacheUser;
import top.lixunda.ecommerce.server.user.api.entity.db.*;
import top.lixunda.ecommerce.server.user.api.entity.dto.UserAddressChgDTO;
import top.lixunda.ecommerce.server.user.api.entity.dto.UserAddressInsertDTO;
import top.lixunda.ecommerce.server.user.api.controller.IUserAddressController;
import top.lixunda.ecommerce.server.user.service.*;

import java.util.List;

/**
 * @author Xumda
 * @version time:2019/12/14 17:47
 * <p>
 * 用户地址管理
 */
@SuppressWarnings({"FieldCanBeLocal", "unused", "WeakerAccess", "UnusedReturnValue"})
@Slf4j
@RestController
public class UserAddressController extends BaseController implements IUserAddressController {

    private final IPositionProvinceService provinceService;

    private final IPositionCityService cityService;

    private final IPositionCountyService countyService;

    private final IPositionTownService townService;

    private final IPositionVillageService villageService;

    private final IUserAddressService userAddressService;

    @Autowired
    public UserAddressController(IPositionProvinceService provinceService,
                                 IPositionCityService cityService,
                                 IPositionCountyService countyService,
                                 IPositionTownService townService,
                                 IPositionVillageService villageService,
                                 IUserAddressService userAddressService) {
        this.provinceService = provinceService;
        this.cityService = cityService;
        this.countyService = countyService;
        this.townService = townService;
        this.villageService = villageService;
        this.userAddressService = userAddressService;
    }

    /**
     * @see IUserAddressController#queryProvinces()
     */
    @Override
    @GlobalTransactional
    public MessageObject<List<PositionProvinceDO>> queryProvinces() {
        List<PositionProvinceDO> provinceList = provinceService.list();
        return getSuccessMessageObject("获取省份信息成功", provinceList);
    }

    /**
     * @see IUserAddressController#queryCitiesByProvince(Long id)
     */
    @Override
    @GlobalTransactional
    public MessageObject<List<PositionCityDO>> queryCitiesByProvince(Long id) {
        List<PositionCityDO> cityList = cityService.list(
                new LambdaQueryWrapper<PositionCityDO>()
                        .eq(PositionCityDO::getProvinceId, id));
        return getSuccessMessageObject("获取县级市信息成功", cityList);
    }

    /**
     * @see IUserAddressController#queryCountiesByCity(Long id)
     */
    @Override
    @GlobalTransactional
    public MessageObject<List<PositionCountyDO>> queryCountiesByCity(Long id) {
        List<PositionCountyDO> countyList = countyService.list(
                new LambdaQueryWrapper<PositionCountyDO>()
                        .eq(PositionCountyDO::getCityId, id));
        return getSuccessMessageObject("获取地区市信息成功", countyList);
    }

    /**
     * @see IUserAddressController#queryTownsByCounty(Long id)
     */
    @Override
    @GlobalTransactional
    public MessageObject<List<PositionTownDO>> queryTownsByCounty(Long id) {
        List<PositionTownDO> townList = townService.list(
                new LambdaQueryWrapper<PositionTownDO>()
                        .eq(PositionTownDO::getCountyId, id));
        return getSuccessMessageObject("获取镇信息成功", townList);
    }

    /**
     * @see IUserAddressController#queryVillagesByTown(Long id)
     */
    @Override
    @GlobalTransactional
    public MessageObject<List<PositionVillageDO>> queryVillagesByTown(Long id) {
        List<PositionVillageDO> villageList = villageService.list(
                new LambdaQueryWrapper<PositionVillageDO>()
                        .eq(PositionVillageDO::getTownId, id));
        return getSuccessMessageObject("获取省市县镇村信息成功", villageList);
    }

    /**
     * @see IUserAddressController#queryDefaultUserAddress()
     */
    @Override
    @GlobalTransactional
    public MessageObject<UserAddressDO> queryDefaultUserAddress() {
        CacheUser userDetail = currentUserCacheNotNull();
        UserAddressDO userAddress = userAddressService.getOne(
                new LambdaQueryWrapper<UserAddressDO>()
                .eq(UserAddressDO::getAccount, userDetail.getAccount())
                .eq(UserAddressDO::getIsDefault, UserAddressDO.CODE_DEFAULT_ADDRESS)
                        .eq(UserAddressDO::getUseable, UserAddressDO.USEABLE),
                false);
        return getSuccessMessageObject("获取默认地址成功", userAddress);
    }

    /**
     * @param id 用户地址id
     * @return 用户地址信息
     */
    @Override
    @GlobalTransactional
    public MessageObject<UserAddressDO> queryAddressById(Long id) {
        if (id == null || id <= 0) {
            return MessageObject.error(UserAddressDO.class, "id不能为空且必须大于0");
        }
        CacheUser userDetail = currentUserCacheNotNull();
        UserAddressDO userAddress = userAddressService.getOne(
                new LambdaQueryWrapper<UserAddressDO>()
                        .eq(UserAddressDO::getId, id)
                        .eq(UserAddressDO::getAccount, userDetail.getAccount())
                        .eq(UserAddressDO::getUseable, UserAddressDO.USEABLE));
        return getSuccessMessageObject("获取默认地址成功", userAddress);
    }

    /**
     * 获取用户所有地址信息
     * @see IUserAddressController#queryAllUserAddress()
     */
    @Override
    @GlobalTransactional
    public MessageObject<List<UserAddressDO>> queryAllUserAddress() {
        CacheUser userDetail = currentUserCacheNotNull();
        List<UserAddressDO> userAddressList = userAddressService.list(
                new LambdaQueryWrapper<UserAddressDO>()
                .eq(UserAddressDO::getAccount, userDetail.getAccount())
                        .eq(UserAddressDO::getUseable, UserAddressDO.USEABLE));
        return getSuccessMessageObject("获取地址成功", userAddressList);
    }

    /**
     * @see IUserAddressController#insertUserAddress(UserAddressInsertDTO userAddressInsertDTO)
     */
    @Override
    @GlobalTransactional
    public MessageObject<UserAddressDO> insertUserAddress(@XumValid UserAddressInsertDTO userAddressInsertDTO) {
        CacheUser userDetail = currentUserCacheNotNull();
        UserAddressDO userAddress = userAddressInsertDTO.toUserAddress();
        // 默认地址，将其他地址设置为非默认地址
        if (UserAddressDO.CODE_DEFAULT_ADDRESS.equals(userAddress.getIsDefault())) {
            userAddressService.update(new LambdaUpdateWrapper<UserAddressDO>()
                    .eq(UserAddressDO::getAccount, userDetail.getAccount())
                    .set(UserAddressDO::getIsDefault, UserAddressDO.CODE_NOT_DEFAULT_ADDRESS));
        }
        userAddress.setAccount(userDetail.getAccount());
        boolean success = userAddressService.save(userAddress);
        return success ? getSuccessMessageObject("保存地址成功", userAddress) :
                getErrorMessageObject("保存地址失败");
    }

    /**
     * @see IUserAddressController#updateUserAddressById(UserAddressChgDTO userAddressChgDTO)
     */
    @Override
    @GlobalTransactional
    public MessageObject<UserAddressDO> updateUserAddressById(@XumValid UserAddressChgDTO userAddressChgDTO) {
        CacheUser userDetail = currentUserCacheNotNull();
        UserAddressDO userAddress = userAddressChgDTO.toUserAddress();
        // 默认地址，将其他地址设置为非默认地址
        if (UserAddressDO.CODE_DEFAULT_ADDRESS.equals(userAddress.getIsDefault())) {
            userAddressService.update(new LambdaUpdateWrapper<UserAddressDO>()
                    .eq(UserAddressDO::getAccount, userDetail.getAccount())
                    .set(UserAddressDO::getIsDefault, UserAddressDO.CODE_NOT_DEFAULT_ADDRESS));
        }
        userAddress.setAccount(userDetail.getAccount());
        boolean success = userAddressService.updateById(userAddress);
        return success ? getSuccessMessageObject("更新地址成功", userAddress) :
                getErrorMessageObject("更新地址失败");
    }

    /**
     * @see IUserAddressController#deleteUserAddressById(Long id)
     */
    @Override
    @GlobalTransactional
    public MessageObject<Boolean> deleteUserAddressById(Long id) {
        if (id == null || id <= 0) {
            return MessageObject.error("id不能为空且必须大于0", false);
        }
        CacheUser detail = currentUserCacheNotNull();
        return userAddressService.remove(
                new LambdaUpdateWrapper<UserAddressDO>()
                .eq(UserAddressDO::getId, id)
                        .eq(UserAddressDO::getAccount, detail.getAccount()))
                ? getSuccessMessageObject("删除地址信息成功") :
                getErrorMessageObject("删除地址信息失败");
    }
}
